<template>
  <!-- 搜索区域 -->
  <ContentWrap>
    <ElForm
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="表名称" prop="tableName">
        <el-input
          v-model="queryParams.tableName"
          placeholder="请输入表名称"
          clearable
          class="!w-240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="表描述" prop="tableComment">
        <el-input
          v-model="queryParams.tableComment"
          placeholder="请输入表描述"
          clearable
          class="!w-240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          type="daterange"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openImportTable()"
          v-hasPermi="['infra:codegen:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" />
          导入
        </el-button>
      </el-form-item>
    </ElForm>
  </ContentWrap>

  <!-- 列表区域 -->
  <ContentWrap>
    <el-table v-loading="listLoading" :data="list">
      <el-table-column label="数据源" prop="dataSourceName" width="150" />
      <el-table-column label="表名称" prop="tableName" width="290" />
      <el-table-column label="表描述" prop="tableComment" min-width="270" show-overflow-tooltip />
      <el-table-column label="实体" prop="className" width="270" />
      <el-table-column label="创建时间" prop="createTime" width="180" />
      <el-table-column label="更新时间" prop="updateTime" width="180" />
      <el-table-column label="操作" fixed="right" width="280">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handlePreview(scope.row)"
            v-hasPermi="['infra:codegen:preview']"
          >
            预览
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleUpdate(scope.row.id)"
            v-hasPermi="['infra:codegen:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['infra:codegen:delete']"
          >
            删除
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleSyncDB(scope.row)"
            v-hasPermi="['infra:codegen:update']"
          >
            同步
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleCodegen(scope.row)"
            v-hasPermi="['infra:codegen:download']"
          >
            生成代码
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 导入库表弹窗 -->
  <ImportTable ref="importTableRef" @success="getList" />
  <!-- 弹窗：预览代码 -->
  <PreviewCode ref="previewRef" />
</template>

<script setup lang="ts">
import * as CodegenApi from '@/api/infra/codegen'
import ImportTable from './ImportTable.vue'
import PreviewCode from './PreviewCode.vue'
import download from '@/utils/download'

defineOptions({ name: 'InfraCodegen' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const { push } = useRouter() // 路由跳转

const queryParams = reactive({
  tableName: undefined,
  tableComment: undefined,
  createTime: [],
  pageNo: 1,
  pageSize: 20
})
const queryFormRef = ref()

const listLoading = ref(false)
const list = ref([]) // 列表数据
const total = ref(0) // 列表数据总条数

const getList = async () => {
  listLoading.value = true
  try {
    const data = await CodegenApi.getCodegenTablePage(queryParams)
    list.value = data.content
    total.value = data.totalElement
  } finally {
    listLoading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 导入操作 */
const importTableRef = ref<InstanceType<typeof ImportTable>>()
const openImportTable = () => {
  importTableRef.value?.open()
}

/** 预览操作 */
const previewRef = ref<InstanceType<typeof PreviewCode>>()
const handlePreview = (row: CodegenApi.CodegenTableVO) => {
  previewRef.value?.open(row)
}

const handleUpdate = (id: number) => {
  push({ path: '/infra/codegen/edit', query: { id: id } })
}

const handleSyncDB = async (row: CodegenApi.CodegenTableVO) => {
  const tableName = row.tableName
  try {
    await message.confirm('确认要强制同步' + tableName + '表结构吗?')
    await CodegenApi.syncCodegenTable(row.id!)
    message.success('同步成功')
  } catch {}
}

const handleCodegen = async (row: CodegenApi.CodegenTableVO) => {
  const data = await CodegenApi.downloadCodegen(row.id!)
  download.zip(data, 'codegen-' + row.className + '.zip')
}

const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CodegenApi.deleteCodegenTable(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

const firstLoad = ref(true)
onActivated(() => { // keepalive组件才会启用，首次装载会在onMounted之后执行，后续从keepalive中被激活也会执行
  if (firstLoad.value) {  // 确保不与onMounted重复执行逻辑
    firstLoad.value = false
    return
  }
  if (history.state?.reload) {
    getList()
  }
})

onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss"></style>
